const {
  $Message
} = require('/component/iView/base/index');

App({
  globalData: {
    wxuserInfo: null,
    baseAPI: "https://www.dabenben.cn:8001",
    examPaperCount: 0,
    questionCount: 0,
    doExamPaperCount: 0,
    doQuestionCount: 0,
    fixedPaper: [],
    pushPaper: [],
    timeLimitPaper: [],
    taskList: [],
    fixedPaperCount: 0,
    taskPaperCount: 0,
    timeLimitPaperCount: 0,
    pushPaperCount: 0,
    pageSize: 2000,
    userInfo: null,
    inportance_notice: [],
    avatarUrl: null,
    gender: null,
    list: {
      isPass: null,
      title: null,
      createTime: null,
      contentlist: "null"
    },
    jinrishici1: "长风破浪会有时，直挂云帆济沧海。",
    examPaperAnswerId: null,
    encParam: null,
    decParam: null,
    userScore: null,
    password: null,
    doExamPaperId: null,
    header: {
      "content-type": "application/x-www-form-urlencoded",
      'Cookie': ''
    },
    //问卷标题
    questionnaireTitle: '',
    //简介
    briefIntroduction: '',
    //昵称
    nickName: "",
    question: [],
    //问卷状态
    state: '',
    createTime: [],
    //问卷ID
    questionnaireId: '',
    version: 0
  },

  onLoad: function () {

    wx.getSystemInfo({
      success: e => {
        this.globalData.screenWidth = e.screenWidth * e.pixelRatio
        this.globalData.screenHeight = e.screenHeight * e.pixelRatio
        this.globalData.pixelRatio = e.pixelRatio
        this.globalData.StatusBar = e.statusBarHeight;
        this.globalData.brand = e.brand;
        let Height = e.windowHeight;
        this.globalData.Height = Height;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },
  onLaunch: function () {
    let _this = this
    const accountInfo = wx.getAccountInfoSync();
    console.log(accountInfo);
    this.globalData.version = accountInfo.miniProgram.version;
    console.log(accountInfo.miniProgram.version) // 插件版本号， 'a.b.c' 这样的形式
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        let Height = e.windowHeight;
        this.globalData.Height = Height;
      }
    })
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    let token = wx.getStorageSync('token')
    const isFir = wx.getStorageSync('isFirst')

    if (!wx.cloud) {
      console.error("请使用2.2.3以上基础库")
    } else {
      wx.cloud.init({
        env: "dabenben-jrvrn"
      })
    }
    if (null == token || token == '') {
      wx.login({
        success(wxres) {
          if (wxres.code) {
            _this.formPost('/api/wx/student/auth/checkBind', {
              "code": wxres.code
            }).then(res => {
              if (res.code == 1) {
                wx.setStorageSync('token', res.response)
                console.log(res.response)
              } else if (res.code == 2) {
                wx.reLaunch({
                  url: '/pages/user/bind/index',
                });
              } else {
                _this.message(res.message, 'error')
              }
            }).catch(e => {
              _this.message(e, 'error')
            })
          } else {
            _this.message(res.errMsg, 'error')
          }
        }
      })
    }
  },
  message: function (content, type) {
    $Message({
      content: content,
      type: type
    });
  },
  formPost: function (url, data) {
    let _this = this
    return new Promise(function (resolve, reject) {
      wx.showNavigationBarLoading();
      wx.request({
        url: _this.globalData.baseAPI + url,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'token': wx.getStorageSync('token')
        },
        method: 'POST',
        data,
        success(res) {

          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            reject('网络出错')
            return false;
          }

          if (res.data.code === 400) {
            let token = res.data.response
            wx.setStorageSync('token', token)
            wx.request({
              url: _this.globalData.baseAPI + url,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'token': wx.getStorageSync('token')
              },
              method: 'POST',
              data,
              success(result) {
                resolve(result.data);
                return true;
              }
            })
          } else if (res.data.code === 401) {
            wx.reLaunch({
              url: '/pages/user/bind/index',
            });
            return false;
          } else if (res.data.code === 500) {
            reject(res.data.message)
            return false;
          } else if (res.data.code === 501) {
            reject(res.data.message)
            return false;
          } else {
            resolve(res.data);
            return true;
          }
        },
        fail(res) {
          reject(res.errMsg)
          return false;
        },
        complete(res) {
          wx.hideNavigationBarLoading();
        }
      })
    })
  }
})